package leeon.mobile.server.bbscache;

import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;

import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import leeon.mobile.BBSBrowser.models.BoardObject;

import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions.Method;

public class QueueService {
	
	private static final String BOARD_QUEUE = "boardQueue";
	private static final String NEW_QUEUE = "newQueue";
	private static final String DELETE_QUEUE = "deleteQueue";
	private static final String PIC_QUEUE = "picQueue";
	
	private static final long DELAY_MILLIS = 9*60*60*1000;
	
	public static void addBoardQueue(BoardObject board) {
		Queue queue = QueueFactory.getQueue(BOARD_QUEUE);
        queue.add(url("/queue/queueBoard").param("board", board.getName()));
	}
	
	public static void addNewQueue(BoardObject board, Date fromDate) {
		Queue queue = QueueFactory.getQueue(NEW_QUEUE);
        queue.add(url("/queue/queueNew").param("board", board.getName())
        		.param("fromDate", Utils.dateToString(fromDate)));
	}
	
	public static void addDeleteQueue(BoardObject board) {
		Queue queue = QueueFactory.getQueue(DELETE_QUEUE);
        queue.add(url("/queue/queueDelete").param("board", board.getName()));
	}
	
	public static void addPicQueueDelay(String path) {
		Queue queue = QueueFactory.getQueue(PIC_QUEUE);
		queue.add(url("/upload" + path).method(Method.GET)
			.param("fromQueue", "true")
			.countdownMillis(DELAY_MILLIS));
	}
	
	public static void addPicQueue(String path) {
		Queue queue = QueueFactory.getQueue(PIC_QUEUE);
		queue.add(url("/upload" + path).method(Method.POST)
			.param("fromQueue", "true"));
	}
	
	public static final String IMG_URL_PATTERN = "http://bbs.fudan.edu.cn/upload[\\w-/\\.]+";
	public static void findUrlPattern(String s, Map<String, String> cache) {
		Pattern p = Pattern.compile(IMG_URL_PATTERN, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(s);
		while (m.find()) {
			String path = m.group().substring(30);
			if (cache != null && cache.containsKey(path)) continue;
			addPicQueue(path);
			cache.put(path, "");
		}
	}
	
//	public static void main(String[] s) {
//		Pattern p = Pattern.compile(IMG_URL_PATTERN, Pattern.CASE_INSENSITIVE);
//		Matcher m = p.matcher("http://bbs.fudan.edu.cn/upload/PIC/2939-112303938.JPG<>>?ddee");
//		while (m.find()) {
//			System.out.println(m.group());
//		}
//	}
}
